package com.bci.pwtz.service.cad;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;

import org.apache.log4j.Logger;

import com.bci.pwtz.common.PwtzConstants;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;


public class ExecuteCADScr {
	private static Logger _log = Logger.getLogger(ExecuteCADScr.class);
	
	/**
	 * 执行scr脚本
	 * @param executeFile upload文件夹下的文件名称（不含后缀）
	 * @return
	 */
	public static String execute(String executeFile){
		
		ComThread.InitSTA();
		//打开cad程序
		_log.debug("正在打开cad程序...");
		ActiveXComponent cad = new ActiveXComponent("AutoCAD.Application");
		_log.debug("打开cad程序完成");
		String outPutFile = null;
		try{
			//执行scr脚本的路径
			String executeFilePath = PwtzConstants.WEB_REAL_PATH+"\\upload\\"+executeFile+".scr";
			//执行JNI的命令
			String conmmandFile = PwtzConstants.WEB_REAL_PATH+"\\cad\\cad.txt";
			//输出文件的路径
			outPutFile = PwtzConstants.WEB_REAL_PATH+"\\upload\\"+executeFile+".dwg";
			
			//创建一个新窗口
			Dispatch window = Dispatch.get(cad,"Documents").toDispatch();
			Dispatch.call(window, "Add");
			
			//获取文档对象
			Dispatch Adoc = Dispatch.get(cad,"ActiveDocument").toDispatch();
			
			//设置字体
			Dispatch font = Dispatch.get(Adoc,"ActiveTextStyle").toDispatch();
			Dispatch.call(font, "SetFont","宋体",false,false,1,0);
			
			//执行命令
			String sendCommand = readFile(conmmandFile, "GBK");
			sendCommand = MessageFormat.format(sendCommand, executeFilePath);
			_log.debug("cad执行命令中...:\n"+sendCommand);
			Dispatch.call(Adoc, "SendCommand",sendCommand);
			_log.debug("cad执行命令完成");
			
			//保存文件
			Dispatch.call(Adoc, "SaveAs", outPutFile);
			_log.debug("cad保存文件:"+outPutFile);
		} finally{
			//关闭当前cad程序
			if(cad != null){
				cad.invoke("Quit",new Variant[0]);
				_log.debug("cad程序成功关闭");
			}
			
			//释放在程序线程中引用的其它com
			ComThread.Release();
		}
		return outPutFile;
	}
	
	public static String readFile(String filePath,String charset){
		StringBuffer info = new StringBuffer();
		try {
			InputStream in = new FileInputStream(filePath);
			
			int len = 0;
			byte[] by = new byte[1024];
			if( (len = in.read(by)) != -1 ){
				info.append(new String(by,0,len,charset));
			}
			
		} catch (Exception e) {
			_log.error(e.getMessage(), e);
		}
		
		return info.toString();
	}
	public static String writeFile(InputStream in,String filePath){
		if(in == null){
			return null;
		}
		
		OutputStream out = null;
		try {
			out = new FileOutputStream(filePath);
			
			int len = 0;
			byte[] by = new byte[1024];
			while( (len = in.read(by)) != -1 ){
				out.write(by,0,len);
			}
			
			out.flush();
			return filePath;
		} catch (Exception e) {
			_log.error(e.getMessage(), e);
		} finally{
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
	
	public static InputStream formUpload(String urlStr, Map<String, String> textMap,  
            Map<String, String> fileMap) {  
        String res = "";  
        HttpURLConnection conn = null;  
        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符  
        try {  
            URL url = new URL(urlStr);  
            conn = (HttpURLConnection) url.openConnection();  
            conn.setConnectTimeout(5000);  
            conn.setReadTimeout(30000);  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            conn.setUseCaches(false);  
            conn.setRequestMethod("POST");  
            conn.setRequestProperty("Connection", "Keep-Alive");  
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");  
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);  
  
            OutputStream out = new DataOutputStream(conn.getOutputStream());  
            // text  
            if (textMap != null) {  
                StringBuffer strBuf = new StringBuffer();  
                Iterator iter = textMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry entry = (Map.Entry) iter.next();  
                    String inputName = (String) entry.getKey();  
                    String inputValue = (String) entry.getValue();  
                    if (inputValue == null) {  
                        continue;  
                    }  
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append(  
                            "\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\""  
                            + inputName + "\"\r\n\r\n");  
                    strBuf.append(inputValue);  
                }  
                out.write(strBuf.toString().getBytes());  
            }  
  
            // file  
            if (fileMap != null) {  
                Iterator iter = fileMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry entry = (Map.Entry) iter.next();  
                    String inputName = (String) entry.getKey();  
                    String inputValue = (String) entry.getValue();  
                    if (inputValue == null) {  
                        continue;  
                    }  
                    File file = new File(inputValue);  
                    String filename = file.getName();  
                    String contentType = new MimetypesFileTypeMap()  
                            .getContentType(file);  
                    if (filename.endsWith(".png")) {  
                        contentType = "image/png";  
                    }  
                    if (contentType == null || contentType.equals("")) {  
                        contentType = "application/octet-stream";  
                    }  
  
                    StringBuffer strBuf = new StringBuffer();  
                    strBuf.append("--").append(BOUNDARY).append(  
                            "\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\""  
                            + inputName + "\"; filename=\"" + filename  
                            + "\"\r\n");  
                    strBuf.append("Content-Type: " + contentType + "\r\n\r\n");  
  
                    out.write(strBuf.toString().getBytes());  
  
                    DataInputStream in = new DataInputStream(  
                            new FileInputStream(file));  
                    int bytes = 0;  
                    byte[] bufferOut = new byte[1024];  
                    while ((bytes = in.read(bufferOut)) != -1) {  
                        out.write(bufferOut, 0, bytes);  
                    }  
                    in.close();  
                }  
            }  
  
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
            out.write(endData);  
            out.flush();  
            out.close();  
            
            return conn.getInputStream();
        } catch (Exception e) {  
            _log.error("发送POST请求出错。" + urlStr, e);
        } finally {  
            /*if (conn != null) {  
                conn.disconnect();  
                conn = null;  
            }  */
        }  
        return null;  
    }  
	
	public static String getMessage(InputStream in) {
		if(in == null){
			return null;
		}
		String res = null;
        try {  
            // 读取返回数据  
            StringBuffer strBuf = new StringBuffer();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
                strBuf.append(line).append("\n");  
            }  
            res = strBuf.toString();  
            reader.close();  
            reader = null;  
        } catch (Exception e) {  
            _log.error("", e);
        } finally {  
            if (in != null) {  
            	try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }  
        }  
        return res;  
    }  
	
	public static String getFileName(String filePath){
		if(filePath != null && filePath.length() > 0){
			int start = filePath.lastIndexOf("/");
			if(start == -1){
				start = 0;
			}
			int end = filePath.lastIndexOf(".");
			if(end == -1){
				end = filePath.length();
			}
			return filePath.substring(start+1,end);
		}
		return null;
	}
}
